package site.wetsion.galio.auth.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import site.wetsion.galio.data.entity.UserDO;
import site.wetsion.galio.data.service.UserService;

/**
 * @author weixin
 * @version 1.0
 * @CLassName RmsAuthenticationManager
 * @date 2019/3/19 8:57 PM
 */
public class RmsAuthenticationManager implements AuthenticationManager {

    private UserService userService;

    public RmsAuthenticationManager(UserService userService) {
        this.userService = userService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.or();
        queryWrapper.eq("email", username);
        UserDO userDO = userService.getOne(queryWrapper);
        if (!userDO.getPassword().equals(password)) {
            throw new BadCredentialsException("密码或用户名错误");
        } else {
            return new UsernamePasswordAuthenticationToken(username, password);
        }
    }
}
